package com.zhanggm.springcloud.jpa.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.zhanggm.springboot.starter.upload.service.FileService;
import com.zhanggm.springboot.starter.upload.util.FileResult;
import com.zhanggm.springcloud.common.ResponseResult;
import com.zhanggm.springcloud.jpa.entity.TbDoctor;
import com.zhanggm.springcloud.jpa.entity.TbUser;
import com.zhanggm.springcloud.jpa.service.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "医生服务接口")
@RestController
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    private TbDoctorService doctorService;

    @Autowired
    private TbDepartService departService;

    @Autowired
    private TbSkillService skillService;

    @Autowired
    private TbAreaService areaService;

    @Autowired
    private TbUserService userService;

    @Autowired
    private FileService fileService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 列表
     * @param doctor
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "分页列表接口",notes = "默认显示5条数据，支持名称、技能、部门查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "页码",dataType = "Integer",required = false),
            @ApiImplicitParam(name = "pageSize",value = "页码",dataType = "Integer",required = false)}
    )
    @ApiResponses({
            @ApiResponse(code = 500,message = "服务端错误"),
            @ApiResponse(code = 404,message = "访问的页面不存在")
    })
    @GetMapping("getPageInfo")
    public Page<TbDoctor> getPageInfo(TbDoctor doctor, @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        return doctorService.getPageInfo(doctor,pageNum,pageSize);
    }

    /**
     * 部门和技能数据
     * @return
     */
    @GetMapping("initData")
    public Map<String,Object> initData(){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("departList",departService.getAll());
        resultMap.put("skillList",skillService.getAll());
//        resultMap.put("shengList",areaService.getListByPid(1));
        resultMap.put("areaTreeAll",areaService.getTreeAll());
        return resultMap;
    }

    /**
     * 保存修改接口
     * @param doctor
     * @return
     */
    @PostMapping("save")
    public boolean save(@RequestBody TbDoctor doctor,HttpServletRequest request){
        if(doctor.getId()==null){
            String token = request.getHeader("token");
            TbUser loginUser = (TbUser)redisTemplate.opsForValue().get(token);
            doctor.setUserId(loginUser.getId());
        }
        return doctorService.save(doctor)>0;
    }

    /**
     * 根据Id查询医生信息
     * @param id
     * @return
     */
    @GetMapping("getById")
    public TbDoctor getById(Integer id){
        TbDoctor doctor = doctorService.getById(id);
        return doctor;
    }

    @GetMapping("getDetailById")
    public TbDoctor getDetailById(Integer id){
        TbDoctor doctor = doctorService.getDetailById(id);
        return doctor;
    }

    /**
     * 根据Id删除
     * @param ids
     * RequestBody {}
     * @return
     */
    @PostMapping("delByIds")
    public boolean delByIds(@RequestBody List<Integer> ids){
        int i = doctorService.delByIds(ids);
        return i>0;
    }

    /**
     * 登录接口
     * @param user
     * @return
     */
    @PostMapping("login")
    public Object login(@RequestBody TbUser user, HttpServletRequest request){
        //查询用户是否存在
        TbUser loginUser = userService.getUserByUsername(user.getUsername());
        if(loginUser==null){
            return ResponseResult.fail(0);
        }
        //密码错误
        if(!loginUser.getPassword().equals(user.getPassword())){
            return ResponseResult.fail(0);
        }
        //登录成功
//        return loginUser.getUsername();
        loginUser.setPassword(null);
        //生成token
        String remoteAddr = request.getRemoteAddr();
        String token = SecureUtil.md5(System.currentTimeMillis() + loginUser.getId() + remoteAddr);
        //把token缓存到redis
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUser));
        redisTemplate.expire(token,60, TimeUnit.SECONDS);
        //给前端返回
        return ResponseResult.success(token);
    }

    @PostMapping("upload")
    public FileResult  upload(@RequestParam("file") MultipartFile file) throws IOException {
        FileResult fileResult = fileService.upload(file);
        return fileResult;
    }
}
